package com.longtop.sp.mapdao.dialect.oracle;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;

import com.longtop.sp.mapdao.Load;
import com.longtop.sp.mapdao.MapVO;
import com.longtop.sp.mapdao.dialect.ConfigProperties;
import com.longtop.sp.mapdao.impl.AbstractOperate;
import com.longtop.sp.mapdao.meta.IPrimaryKey;
import com.longtop.sp.mapdao.meta.TableMetaData;
import com.longtop.sp.mapdao.meta.TableMetaDataPool;

public class OracleLoad extends AbstractOperate implements Load{
	
	public MapVO load(Map ids) throws Exception {
		IPrimaryKey pk = this.pkFactory.createPrimarykey(jdbcTemplate,
				tableName,null);
		TableMetaData rsmt = TableMetaDataPool.getMetaData(jdbcTemplate,
				tableName);
		return loadByPk(ids, pk, rsmt);
	}

	private MapVO loadByPk(Map ids, IPrimaryKey pk, TableMetaData rsmt)
			throws SQLException {
		String id = pk.getPrimaryKeyAndValue(ids, rsmt);
		String sql ="SELECT * FROM "+tableName+ " WHERE " + id;
		List<Map> l = jdbcTemplate.queryForList(sql);
		if(l != null && !l.isEmpty()){
			Map m = l.get(0);
			MapVO vo = new MapVO(tableName,m);
			return vo;
		}
		return null;
	}

	@Override
	public int executeImpl() throws Exception {
		return 0;
	}

	public MapVO loadBySinglePk(Object id) throws Exception {
		IPrimaryKey pk = this.pkFactory.createPrimarykey(jdbcTemplate,
				tableName,ConfigProperties.getValue());
		TableMetaData rsmt = TableMetaDataPool.getMetaData(jdbcTemplate,
				tableName);
		String pkName = pk.getPrimaryKey(0);
		Map m = new HashMap();
		m.put(pkName, id);
		return loadByPk(m, pk, rsmt);
		
	}
	
}
